package pdd;

import sort.Util;

import java.util.Arrays;
import java.util.Scanner;

public class T4 {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        int n = sc.nextInt();
        int m = sc.nextInt();
        int len = n*m;
        int[] comeArray = new int[len];
        int[] hArray = new int[len];
        int index = 0;
        while (index < len) {
            comeArray[index] = index;
            hArray[index++] = sc.nextInt();
        }
        reverseArray(comeArray);
        reverseArray(hArray);
        sortArray(comeArray, hArray);

        index = 0;
        int result = 0;
        while(index < len) {
            int leftIndex = index;
            int rightIndex = index + m-1;
            index += m;
            for (int i=rightIndex; i>leftIndex; i--) {
                for (int j=i; j>=leftIndex; j--) {
                    if (comeArray[i] > comeArray[j]) {
                        result++;
                    }
                }
            }
        }
        System.out.println(result);

    }

    private static void sortArray(int[] comeArray, int[] hArray) {
        int len = comeArray.length;

        for (int i = 1; i < len; i++) {
            for (int j = i - 1; j >= 0; j--) {  // 从右往左走
                if (hArray[j] <= hArray[j+1]) {   // 左边是排好序的
                    break;
                }
                if (hArray[j] > hArray[j + 1]) {  // 如果前一个大于后一个，交换
                    swap(hArray, j, j+1);
                    swap(comeArray, j, j+1);
                }
            }
        }
    }

    private static void reverseArray(int[] array) {
        int len = array.length;

        int[] newArray = new int[len];
        System.arraycopy(array, 0, newArray, 0, len);

        for (int i = 0; i < len; i++) {
            array[i] = newArray[len-i-1];
        }
    }

    public static void swap(int[] array, int i, int j) {
        int temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
}
